package net.zoneland.knowledge.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import net.zoneland.knowledge.config.EsConfig;
import net.zoneland.knowledge.controller.bean.OperationResult;
import net.zoneland.knowledge.dao.RobotInfoMapper;
import net.zoneland.knowledge.model.RobotInfoExample;
import net.zoneland.knowledge.service.EsService;
import net.zoneland.knowledge.utils.FunctionUtils;

/**
 * 健康检查地址.
 * @author zmq
 * @Date 2022/1/11 9:05
 */
@RestController
public class HealthCheckController {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckController.class);

    /**
     * 机器人
     */
    @Autowired
    private RobotInfoMapper robotInfoMapper;

    /**
     * es配置
     */
    @Autowired
    private EsConfig esConfig;

    @Autowired
    private EsService esService;

    /**
     * 健康检查
     * @return
     */
    @GetMapping("/healthcheck")
    public Map<String, OperationResult> healthCheck() {
        final Map<String, OperationResult> map = new HashMap<>();
        map.put("primary",new FunctionUtils<RobotInfoExample, List>().checkDataSource(robotInfoMapper::selectByExample, null, "primary"));
        map.put("es",checkEs());
        return map;
    }

    private OperationResult checkEs() {
        final OperationResult res = new OperationResult();
        res.setSuccess(true);
        try {
            esService.checkHealth(esConfig);
        } catch (Exception e) {
            res.setSuccess(false);
            res.setMsg(e.getMessage());
            LOGGER.error("checkEs error", e);
        }
        return res;
    }

}
